// pages/Song/Song.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 歌曲信息
        song:{},
        // 歌曲id
        id:'',
        // 歌曲总时间
        time:'',
        // 歌曲url
        music:'',
        // 当前播放时间
        currentTime:'00:00',
        // 定时器检测进度条
        timer:null,
        // 进度条比例
        width:0,
        // 是否播放音乐
        play:true, 
        // 循环状态
        loop:1,
        // 是否展示音乐列表弹框
        show:false,
        // 歌曲列表
        songlist:[],
        // 显示歌词
        showLyric:false,
        // 歌词数组
        lyric:[],
        // 歌词滚动距离
        scrollTop:0,
        // 当前歌词索引
        currentIndex:0
    },
    
    // 获取歌曲详情
    async getSongDetail(){
        const res = await wx.p.request({
            url:`${wx.root}/song/detail`,
            data:{
                ids:this.data.id,
            }
        })
        this.setData({
            song:res.data.songs[0],
            time:this.min(res.data.songs[0].dt)+':'+this.sec(res.data.songs[0].dt)
        })
        wx.setNavigationBarTitle({
          title: this.data.song.name,
        })
        this.getSong()
    },
    // 获取歌曲url
    async getSong(){
        const res = await wx.p.request({
            url:`${wx.root}/song/url`,
            data:{
                id:this.data.id
            }
        })
        this.setData({
            music:res.data.data[0].url
        })  
        wx.setStorageSync('Music', this.data.id)
        this.addSongs(this.data.id)
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.title = this.data.song.name
        backgroundAudioManager.epname = this.data.song.al.name
        backgroundAudioManager.singer = this.data.song.ar[0].name
        backgroundAudioManager.src=this.data.music
        this.play()
        this.getLyric()
    },
    // 播放歌曲
    play(){
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.play()
        this.setData({
            timer:setInterval(() => {
                this.setData({
                    currentTime:this.min(parseInt(backgroundAudioManager.currentTime*1000))+':'+this.sec(parseInt(backgroundAudioManager.currentTime*1000)),
                    width:backgroundAudioManager.currentTime*1000/this.data.song.dt*100
                })
            },100),
            play:true,
        })
    },
    // 暂停播放
    pause(){
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.pause()
        clearInterval(this.data.timer)
        this.setData({
            timer:null,
            play:false
        })
    },
    // 时间转换
    min(min){
        if(parseInt(min/60000) < 10)
            return '0'+parseInt(min/60000);
        else return parseInt(min/60000)
    },
    sec(sec){
        let x = parseInt(sec/60000);
        let y = parseInt(sec/1000-x*60);
        if(y < 10) return '0'+y;
        else return y;
    },
    // 改变播放状态
    changePlayState(){
        if(this.data.play){
            this.pause()
        }else{
            this.play()
        }
    },
    // 点击改变进度条   
    changePositionInBar(e){
        let left = (e.detail.x-55)/275*100
        if(left < 0) left = 0
        if(left > 100) left = 100 
        this.setData({
            width:left
        })
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.seek(
            this.data.song.dt*this.data.width/100000
        )
    },
    // 拖拽进度条
    changePosition(e){
        clearInterval(this.data.timer)
        let left = (e.touches[0].clientX-55)/275*100
        if(left < 0) left = 0
        else if(left > 100) left = 100
        this.setData({
            width:left
        })
    },
    // 释放进度条
    stopChange(e){
        let left = e.target.offsetLeft
        if(left < 0) left = 0
        if(left > 275) left = 275
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        backgroundAudioManager.seek(
            this.data.song.dt*this.data.width/100000
        )
        this.play()
    },
    // 打开我的歌曲列表
    showList(){
        this.setData({
            show:true
        })
    },
    // 关闭我的歌曲列表
    onClose(){
        this.setData({
            show:false
        })
    },
    // 改变播放循环状态
    changeLoop(){
        let timer2
        clearTimeout(timer2)
        wx.hideToast({
          success: (res) => {},
        })
        this.setData({
            loop:(this.data.loop+1)%3
        })
        let title
        if(this.data.loop == 1) title="循环播放"
        else if(this.data.loop == 2) title="随机播放"
        else title="单曲循环"
        wx.showToast({
          title: title,
        })
        timer2 = setTimeout(() => {
            wx.hideToast({
            success: (res) => {},
            })    
        }, 1000);
        
    },
    // 添加歌曲至歌曲列表
    addSongs(id){
        const songlist = wx.getStorageSync('Songlist')  || []
        let flag = 1;
        songlist.forEach(item=>{
            if(item == id) flag = 0;
        })
        if(flag == 1){
            songlist.push(id)
            wx.setStorageSync('Songlist', songlist)    
            
        }
        this.getSonglist()
    },
    // 获取歌曲列表
    async getSonglist(){
        const list = wx.getStorageSync('Songlist') || []
        let s = ""
        for (let i = 0; i < list.length; i++) {
            const item = list[i];
            s += item
            if(i != list.length-1) s += ","
        }
        const res = await wx.p.request({
            url:`${wx.root}/song/detail`,
            data:{
                ids:s
            }
        })
        this.setData({
            songlist:res.data.songs
        })

    },
    // 删除歌曲
    deleteMusic(e){
        let index = e.currentTarget.dataset.index
        const list = wx.getStorageSync('Songlist')
        list.splice(index,1)
        if(list.length == 0){
            this.setData({
                songlist:[]
            })
            wx.setStorageSync('Songlist', [])
        }else{
            wx.setStorageSync('Songlist', list)
            this.getSonglist()    
        }
        
    },
    // 切换歌曲
    changeMusic(e){
        let id = e.currentTarget.dataset.id
        if(id == this.data.id) return
        this.setData({
            id:id
        })
        this.getSongDetail()
    },
    // 改变歌词显示状态
    changeLyric(){
        this.setData({
            showLyric:!this.data.showLyric

        })
    },
    // 获取歌词
    async getLyric(){
        const res = await wx.p.request({
            url:`${wx.root}/lyric`,
            data:{
                id:this.data.id
            }
        })
        console.log(res.data);
        const lyric = res.data.lrc.lyric
        const list = []
        let time = ""
        let text = ""
        let isTime = true
        for (let i = 1; i < lyric.length; i++) {
            const s = lyric[i]
            if(s == '[' && i != 0){
                let p = {
                    time:'',
                    text:'',
                }
                
                p.time = this.TimeChange(time)
                p.text = text
                if(p.text.length > 2)
                    list.push(p)
                time = ""
                text = ""
                isTime = true
            }else if(s == ']'){
                isTime = false
            }else{
                if(isTime){
                    time += s
                }else text += s
            }
        }
        
        this.setData({
            lyric:list
        })
    },
    // 时间转换
    TimeChange(time){
        let t = time.split(':')
        let min = parseInt(t[0])
        let sec = parseFloat(t[1])
        return min*60+sec

    },
    // 歌词滚动监听
    watchLyric(){
        const backgroundAudioManager = wx.getBackgroundAudioManager()
        // console.log(backgroundAudioManager.currentTime);
        setInterval(() => {
            for(let i = 0;i < this.data.lyric.length;i++){
                let item = this.data.lyric[i]
                if(Math.abs(backgroundAudioManager.currentTime - item.time) < 0.5){
                    this.setData({
                        scrollTop:(i-4)*39.8*2+'rpx',
                        currentIndex:i
                    })
                    break
                }
                if(item.time > backgroundAudioManager.currentTime) break
                
            }
        }, 200);
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            id:options.id
        })
        this.getSongDetail()
        this.watchLyric()

    },
    test(e){
        console.log(e);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})